import { createSlice, PayloadAction } from "@reduxjs/toolkit";

import { BASE, isDev } from "../utils/request";

export const BROKER_URL =
  (isDev ? "ws://" : "wss://") +
  (window.location.hostname + (isDev ? ":9091/" : ":9090/api/")) +
  "ws";

export type WebSocketMsg = {
  msg: string;
  sender: string;
  receiver: string;
};

const subscribeList: string[] = [];

export const socketSlice = createSlice({
  name: "websocket",
  initialState: {
    showModal: false,
    connected: false,
    subscribeList,
    // msg,
  },
  reducers: {
    removeAllSubscribes(state, action: PayloadAction<void>) {
      return {
        ...state,
        subscribeList: [],
      };
    },
    removeSubscribe(state, action: PayloadAction<string>) {
      return {
        ...state,
        subscribeList: subscribeList.filter((val) => val !== action.payload),
      };
    },
    addSubscribe(state, action: PayloadAction<string>) {
      return {
        ...state,
        subscribeList: [...subscribeList, action.payload],
      };
    },
    updateConnection(state, action: PayloadAction<boolean>) {
      // if (!action.payload) stompClient = null;
      return {
        ...state,
        connected: action.payload,
      };
    },
    setShowModal(state, action: PayloadAction<boolean>) {
      return {
        ...state,
        showModal: action.payload,
      };
    },
    // greet(state, action: PayloadAction<Partial<WebSocketMsg>>) {
    //   if (stompClient === null) return;
    //   stompClient.send(
    //     "/app/identity",
    //     {},
    //     JSON.stringify({
    //       msg: action.payload.msg,
    //       sender: "master",
    //     })
    //   );

    //   return {
    //     ...state,
    //   };
    // },
  },
  extraReducers: (builder) => {
    // builder.addCase(disconnect.fulfilled, (state, action) => {
    //   return {
    //     ...state,
    //     connected: false,
    //   };
    // });
    // builder.addCase(connect.fulfilled, (state, action) => {
    //   // stompClient.ws.onclose = ()=>{
    //   // }
    //   return {
    //     ...state,
    //     connected: true,
    //   };
    // });
  },
});

export const socketReducer = socketSlice.reducer;

export const {
  // greet,
  setShowModal,
  updateConnection,
  addSubscribe,
  removeSubscribe,
} = socketSlice.actions;
